package com.lucker.service.push.web;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONObject;
import com.lucker.common.model.SocketSendMsgObj;
import com.lucker.common.util.AESCBCUtil;
import com.lucker.common.util.AESUtil;
import com.lucker.common.util.CommonStr;
import com.lucker.common.util.EncryptUtil;
import com.lucker.service.push.socket.SocketService;
import com.lucker.service.push.socket.SocketServiceImpl;

public class CustomMessageHandle extends Thread {
	
	
	Logger logger = LoggerFactory.getLogger(CustomMessageHandle.class);
	
	public Socket socket = null;
	public String send_data = null;
	String targetId = null;
	public static Map<String,List<Socket>> socketMap = new HashMap<String, List<Socket>>();
		
	@Autowired
	SocketService socketService;
	
	public CustomMessageHandle(Socket socket) {
		this.socket = socket;
	}
	public void run() {
    	try {
    		BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    		while(true) {
    			if((send_data = reader.readLine()) != null) {
    				//logger.error("SOCKET连接数据解密前: ---------------------" + send_data);
//    				send_data = EncryptUtil.decrypt(send_data, CommonStr.SOCKET_DATA_SIGN);
    				//send_data = AESUtil.decryptBase642String(send_data, CommonStr.SOCKET_DATA_IV, CommonStr.SOCKET_DATA_IV);
    				send_data = AESCBCUtil.decrypt(send_data);
    				//logger.error("SOCKET连接数据解密后: ---------------------" + send_data);
    				SocketSendMsgObj sendObj = null;
    				try {
    					sendObj = JSONObject.parseObject(send_data, SocketSendMsgObj.class);
					} catch (Exception e) {
						logger.error("SOCKET 请求数据转换对象发生错误 {}", e.getMessage(),e);
						PrintWriter pw = null;
						try {
							pw = new PrintWriter(socket.getOutputStream());
							pw.println("***请求数据错误,不是合法的JSON字符串");
							pw.flush();
						} finally {
							if (pw != null) {
								pw.close();
							}
						}
						socket.close(); //断开SOCKET连接
					}
    				targetId = sendObj.getCaiId();
    				if(StringUtils.isBlank(targetId)) {
    					logger.error("***SOCKET 请求数据无法获取 caiId 属性 {}");
    					 //输出提示并关闭SOCKET
    					 PrintWriter pw = null;
                         try {
                        	 pw = new PrintWriter(socket.getOutputStream());
                             pw.println("SOCKET连接参数中CAI_ID不能为空, 服务器拒绝!");
                             pw.flush();                             
                         }finally {
							if(pw != null) {
								pw.close();
							}
						}
                        socket.close();
    				}
    				
    				logger.error("***SOCKET连接成功一个 CAI_ID : {}",targetId);
    				List<Socket> list = CustomMessageHandle.socketMap.get(targetId);
    				if(list == null) {
    					list = new ArrayList<Socket>();
    				}
    				list.add(socket);
    				CustomMessageHandle.socketMap.put(targetId, list);
    				if(CollectionUtils.isNotEmpty(list)) {
    					for(Socket _socket : list) {
        					if(socket != _socket ){
                                //获取对象的输出流
                                //PrintWriter pw;
                                //pw = new PrintWriter(_socket.getOutputStream());
                                //写入信息返回到客户端
                                //pw.println("server message : " + targetId);
                                //pw.flush();
                            }
        				}
    				}
    			}
    		}
		} catch (Exception e) {
			if(!StringUtils.isBlank(targetId)) {
				//socketService.removeDisabledSocket(socket, targetId);
				logger.error("彩种ID" + targetId + " 的SOCKET发生错误,从服务器SOCKET池中删除....... ，异常: {} " , e);
			}
			
		}
    }
	
}
